import {
    ensureGroupAndPlayerExist,
    formatCurrency,
    getConfig,
    getPlayerData,
    storagePlayerData
} from "../function/function.js";

export class Bank extends plugin {
    constructor() {
        super({
            name: '[Sm]银行',
            dsc: '银行功能 - 提供存取款、信用等级管理和利息',
            event: 'message',
            priority: 1,
            rule: [
                { reg: /^[#\/]存款\s*(\d+)$/, fnc: 'deposit' },
                { reg: /^[#\/]取款\s*(\d+)$/, fnc: 'withdraw' },
                { reg: /^[#\/]升级信用$/, fnc: 'upgradeCredit' },
                { reg: /^[#\/]银行信息$/, fnc: 'bankInfo' },
                { reg: /^[#\/]领取利息$/, fnc: 'collectInterest' },
                { reg: /^[#\/]转账\s*(\d+)$/, fnc: 'transfer' },
                { reg: /^[#\/]一键升级信用$/, fnc: 'autoUpgradeCredit' }
            ]
        })
    }

    /**
     * 初始化用户的银行数据
     * @param {Object} userData - 用户数据对象
     * @returns {Object} 初始化后的用户数据
     */
    async initBankData(userData) {
        const config = getConfig();

        // 确保currency是数字
        if (!userData.currency || isNaN(Number(userData.currency))) {
            userData.currency = 0;
        } else {
            userData.currency = Number(userData.currency);
        }

        // 初始化或修复bank数据
        if (!userData.bank || typeof userData.bank !== 'object') {
            userData.bank = {};
        }

        const bank = userData.bank;

        // 确保所有bank字段都是有效数字
        bank.balance = !bank.balance || isNaN(Number(bank.balance)) ? 0 : Number(bank.balance);
        bank.level = !bank.level || isNaN(Number(bank.level)) ? config.bank.initialLevel : Number(bank.level);
        bank.limit = !bank.limit || isNaN(Number(bank.limit)) ? config.bank.initialLimit : Number(bank.limit);
        bank.upgradePrice = !bank.upgradePrice || isNaN(Number(bank.upgradePrice))
            ? config.bank.initialUpgradePrice : Number(bank.upgradePrice);
        bank.lastInterestTime = !bank.lastInterestTime || isNaN(Number(bank.lastInterestTime))
            ? Math.floor(Date.now() / 1000) : Number(bank.lastInterestTime);

        return userData;
    }

    /**
     * 检查是否在群聊中使用命令
     * @param {Object} e - 事件对象
     * @returns {boolean} 是否需要继续执行
     */
    checkGroupMessage(e) {
        if (!e.isGroup) {
            e.reply(['该功能只能在群内使用']);
            return false;
        }
        return true;
    }

    /**
     * 存款功能
     * @param {Object} e - 事件对象
     */
    async deposit(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        const amount = parseInt(e.msg.match(/\d+/)[0]);
        if (isNaN(amount) || amount <= 0) {
            return e.reply(['请输入正确的存款金额']);
        }

        // 检查余额和存储上限
        if (amount > userData.currency) {
            return e.reply(['余额不足']);
        }

        const remainingSpace = userData.bank.limit - userData.bank.balance;
        if (amount > remainingSpace) {
            return e.reply([
                `存款失败！当前存储上限为${userData.bank.limit}金币\n`,
                `当前存款：${userData.bank.balance}金币\n`,
                `可存入：${remainingSpace}金币\n`,
                '可通过升级信用等级提升存储上限'
            ]);
        }

        // 执行存款操作
        userData.currency = formatCurrency(userData.currency - amount);
        userData.bank.balance = formatCurrency(userData.bank.balance + amount);
        storagePlayerData(ID[1], ID[0], userData);

        return e.reply([
            `存款成功！存入${amount}金币\n`,
            `当前存款：${userData.bank.balance}金币\n`,
            `当前余额：${userData.currency}金币`
        ]);
    }

    // 取款
    async withdraw(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        const amount = parseInt(e.msg.match(/\d+/)[0]);
        if (isNaN(amount) || amount <= 0) return e.reply(['请输入正确的取款金额']);

        if (amount > userData.bank.balance) return e.reply(['存款余额不足']);

        userData.currency = formatCurrency(userData.currency + amount);
        userData.bank.balance = formatCurrency(userData.bank.balance - amount);
        storagePlayerData(ID[1], ID[0], userData);

        return e.reply([
            `取款成功！取出${amount}金币\n`,
            `当前存款：${userData.bank.balance}金币\n`,
            `当前余额：${userData.currency}金币`
        ]);
    }

    /**
     * 升级信用等级
     * @param {Object} e - 事件对象
     */
    async upgradeCredit(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        const config = getConfig();
        const upgradePrice = userData.bank.upgradePrice;

        if (userData.currency < upgradePrice) {
            return e.reply([
                `升级失败！升级需要${upgradePrice}金币\n`,
                `当前余额：${userData.currency}金币`
            ]);
        }

        // 执行升级操作
        userData.currency = formatCurrency(userData.currency - upgradePrice);
        userData.bank.level += 1;
        userData.bank.limit = Math.floor(userData.bank.limit * config.bank.limitIncreaseMulti);
        userData.bank.upgradePrice = Math.floor(upgradePrice * config.bank.upgradePriceMulti);

        storagePlayerData(ID[1], ID[0], userData);

        return e.reply([
            `升级成功！当前信用等级：${userData.bank.level}\n`,
            `当前存储上限：${userData.bank.limit}金币\n`,
            `下次升级费用：${userData.bank.upgradePrice}金币\n`,
            `当前余额：${userData.currency}金币`
        ]);
    }

    // 计算利息
    async calculateInterest(balance, lastInterestTime, config) {
        // 确保输入值是数字
        balance = Number(balance);
        lastInterestTime = Number(lastInterestTime);

        if (isNaN(balance) || balance <= 0 || isNaN(lastInterestTime)) {
            return 0;
        }

        const currentTime = Math.floor(Date.now() / 1000);
        const hoursPassed = Math.floor((currentTime - lastInterestTime) / 3600);

        if (hoursPassed < 1) return 0;

        const effectiveHours = Math.min(hoursPassed, config.bank.maxInterestTime);
        const interestRate = Number(config.bank.interestRate);

        if (isNaN(interestRate)) {
            logger.error('利率配置无效');
            return 0;
        }

        const interest = balance * (interestRate * effectiveHours);
        return formatCurrency(interest);
    }

    // 领取利息功能
    async collectInterest(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        const config = getConfig();
        const interest = await this.calculateInterest(
            userData.bank.balance,
            userData.bank.lastInterestTime,
            config
        );

        if (interest <= 0) {
            return e.reply(['当前没有可领取的利息，每小时结算一次']);
        }

        // 更新数据
        userData.currency = formatCurrency(Number(userData.currency) + interest);
        userData.bank.lastInterestTime = Math.floor(Date.now() / 1000);
        storagePlayerData(ID[1], ID[0], userData);

        return e.reply([
            `成功领取利息${interest}金币\n`,
            `当前存款：${userData.bank.balance}金币\n`,
            `当前余额：${userData.currency}金币`
        ]);
    }

    // 查看银行信息
    async bankInfo(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        const config = getConfig();
        const interest = await this.calculateInterest(
            userData.bank.balance,
            userData.bank.lastInterestTime,
            config
        );

        return e.reply([
            `=====银行信息=====\n`,
            `信用等级：${userData.bank.level}\n`,
            `当前存款：${userData.bank.balance}金币\n`,
            `存储上限：${userData.bank.limit}金币\n`,
            `升级费用：${userData.bank.upgradePrice}金币\n`,
            `当前余额：${userData.currency}金币\n`,
            `可领利息：${interest}金币\n`,
            `利率说明：每小时${config.bank.interestRate * 100}%，最多计算${config.bank.maxInterestTime}小时`
        ]);
    }

    // 转账功能
    async transfer(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];
        const config = getConfig();

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        // 从消息中提取金额
        const amount = parseInt(e.msg.match(/转账\s*(\d+)/)[1]);

        // 获取@提及的用户ID
        if (!e.at) {
            return e.reply('请使用@指定要转账的用户');
        }
        const targetId = e.at;

        // 验证目标用户
        const memberInfo = (await Bot.pickGroup(ID[1]).getMemberMap()).get(Number(targetId));
        if (!memberInfo) return e.reply('目标用户不存在');
        if (targetId == ID[0]) return e.reply('不能给自己转账');

        // 验证转账金额
        if (amount < config.transfer.minAmount) {
            return e.reply(`转账金额不能低于${config.transfer.minAmount}金币`);
        }

        // 计算手续费和总扣除
        const fee = Math.ceil(amount * config.transfer.feeRate);
        const totalDeduct = amount + fee;

        if (userData.currency < totalDeduct) {
            return e.reply(`余额不足，需要${totalDeduct}金币（含手续费${fee}）`);
        }

        // 执行转账
        try {
            // 扣除转出方金额
            userData.currency = formatCurrency(userData.currency - totalDeduct);
            storagePlayerData(ID[1], ID[0], userData);

            // 增加接收方金额
            ensureGroupAndPlayerExist(ID[1], targetId, memberInfo.card || memberInfo.nickname);
            let targetData = await getPlayerData(ID[1], targetId);
            targetData.currency = formatCurrency(targetData.currency + amount);
            storagePlayerData(ID[1], targetId, targetData);

            return e.reply([
                `成功转账${amount}金币给${memberInfo.nickname}\n`,
                `手续费：${fee}金币\n`,
                `剩余余额：${userData.currency}金币`
            ]);
        } catch (error) {
            logger.error('转账失败:', error);
            return e.reply('转账处理失败，请稍后再试');
        }
    }

    /**
     * 自动升级信用等级
     * @param {Object} e - 事件对象
     */
    async autoUpgradeCredit(e) {
        if (!this.checkGroupMessage(e)) return;
        const ID = [e.user_id, e.group_id];

        ensureGroupAndPlayerExist(ID[1], ID[0], e.sender.card || e.sender.nickname);
        let userData = await getPlayerData(ID[1], ID[0]);
        userData = await this.initBankData(userData);

        const config = getConfig();
        let totalSpent = 0;
        let upgrades = 0;
        let currentLevel = userData.bank.level;
        let currentUpgradePrice = userData.bank.upgradePrice;

        // 循环计算可升级次数
        while (userData.currency >= currentUpgradePrice) {
            userData.currency = formatCurrency(userData.currency - currentUpgradePrice);
            totalSpent += currentUpgradePrice;
            upgrades++;

            // 更新等级和价格
            userData.bank.level++;
            userData.bank.limit = Math.floor(userData.bank.limit * config.bank.limitIncreaseMulti);
            currentUpgradePrice = Math.floor(currentUpgradePrice * config.bank.upgradePriceMulti);
            userData.bank.upgradePrice = currentUpgradePrice;
        }

        if (upgrades === 0) {
            return e.reply([
                `升级失败！当前升级需要${currentUpgradePrice}金币\n`,
                `当前余额：${userData.currency}金币`
            ]);
        }

        storagePlayerData(ID[1], ID[0], userData);

        return e.reply([
            `一键升级成功！\n`,
            `共升级 ${upgrades} 次\n`,
            `当前信用等级：Lv.${userData.bank.level}\n`,
            `总花费：${totalSpent}金币\n`,
            `剩余余额：${userData.currency}金币\n`,
            `下次升级费用：${currentUpgradePrice}金币\n`,
            `当前存储上限：${userData.bank.limit}金币`
        ]);
    }
} 